package com.zhenhe.interceptor;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.zhenhe.core.common.entity.RespJson;
import com.zhenhe.core.common.global.Global;
import com.zhenhe.core.common.global.signIn.LoginInfoUtil;
import com.zhenhe.core.common.utils.framework.RespJsonFactory;
import com.zhenhe.core.common.utils.http.IPUtil;
import com.zhenhe.core.modules.service.LoginService;

public class CommonInterceptor extends HandlerInterceptorAdapter{

	private static final Logger log = LoggerFactory.getLogger(CommonInterceptor.class);
	
	@Value("${pass.url}")
	private String passUrl;
	
	@Resource
	private LoginService loginService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		String agent = request.getHeader("User-Agent");
		//if(agent.contains("Linux")||agent.contains("Android")){
		/*if(agent.contains("Linux")){
			response.getWriter().write("ok222222");
			response.getWriter().flush();
			response.getWriter().close();
			return false;
		}*/
		
		String[] split = passUrl.split(",");
		String uri = request.getRequestURI();
		for(String s : split){
			if(uri.contains(s)){
				//说明在通过名单里
				return true;
			}
		}
//		if(!loginService.inLoginTime()){
//			response.setStatus(HttpStatus.SC_FORBIDDEN);
//			PrintWriter writer = response.getWriter();
//			writer.write("<script>var w ; if(window.parent){w=window.parent;}else{w=window};w.location.href='"+request.getContextPath()+"'</script>");
//			writer.flush();
//			writer.close();
//			return false;
//		}
		
		LoginInfoUtil.copyLoginToThread(request);
		MDC.put("user", LoginInfoUtil.getLoginInfo().getLoginName());
		if(LoginInfoUtil.isSignIn()){
			log.debug("请求url:{},ip:{}", request.getRequestURI(),IPUtil.getIp(request));
			return true;
		}
		log.debug("用户未登陆");
		
		response.setStatus(HttpStatus.SC_FORBIDDEN);
		PrintWriter writer = response.getWriter();
		writer.write("<script>var w ; if(window.parent){w=window.parent;}else{w=window};w.location.href='"+request.getContextPath()+"'</script>");
		writer.flush();
		writer.close();
		return false;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		try{
			if(ex!=null){
				log.error("系统出错", ex);
				response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Type", "application/json;charset=UTF-8");
				PrintWriter writer = response.getWriter();
				RespJson json = RespJsonFactory.buildFailure("system.error");
				writer.write(JSONObject.toJSONString(json));
				writer.flush();
				writer.close();
			}
		}finally{
			LoginInfoUtil.removeLoginInfo();
			MDC.remove("user");
		}
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		request.setAttribute("branchRole", Global.getBranchRoleId());
	}
}
